package com.kldy8.kldyw.logre;

import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.kldy8.kldyw.R;
import com.kldy8.kldyw.SystemSet;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Request;

public class LoginApi implements Callback {
	private static final int MSG_AUTH_CANCEL = 1;
	private static final int MSG_AUTH_ERROR= 2;
	private static final int MSG_AUTH_COMPLETE = 3;

	private static final int MSG_RETURN_TO_LOGIN = 4;

	private static final int MSG_RETURN_TO_REG = 5;

	private static final int MSG_NET_ERROR = 6;


	private OnLoginListener loginListener;
	private String platform;
	private Context context;
	private Handler handler;

	public LoginApi() {
		handler = new Handler(Looper.getMainLooper(), this);
	}

	public void setPlatform(String platform) {
		this.platform = platform;
	}

	public void setOnLoginListener(OnLoginListener login){
		this.loginListener=login;
	}

	public void login(Context context) {
		this.context = context.getApplicationContext();
		if (platform == null) {
			return;
		}

		//初始化SDK
		ShareSDK.initSDK(context);
		Platform plat = ShareSDK.getPlatform(platform);
		if (plat == null) {
			return;
		}

		if (plat.isAuthValid()) {
			plat.removeAccount(true);
			return;
		}

		//使用SSO授权，通过客户单授权
		plat.SSOSetting(false);
		plat.setPlatformActionListener(new PlatformActionListener() {
			public void onComplete(Platform plat, int action,HashMap<String, Object> res) {
				if (action == Platform.ACTION_USER_INFOR) {
					Message msg = new Message();
					msg.what = MSG_AUTH_COMPLETE;
					msg.arg2 = action;
					msg.obj =  new Object[] {plat.getName(), res};
					handler.sendMessage(msg);
				}
			}

			public void onError(Platform plat, int action, Throwable t)
			{
				if (action == Platform.ACTION_USER_INFOR) {
					Message msg = new Message();
					msg.what = MSG_AUTH_ERROR;
					msg.arg2 = action;
					msg.obj = t;
					handler.sendMessage(msg);
				}
				t.printStackTrace();
			}

			public void onCancel(Platform plat, int action) {
				if (action == Platform.ACTION_USER_INFOR) {
					Message msg = new Message();
					msg.what = MSG_AUTH_CANCEL;
					msg.arg2 = action;
					msg.obj = plat;
					handler.sendMessage(msg);
				}
			}
		});
		plat.showUser(null);
	}

	/**处理操作结果*/
	public boolean handleMessage(Message msg) {
		switch(msg.what) {
			case MSG_AUTH_CANCEL: {
				// 取消
				String text = context.getString(R.string.cancel);
				Toast.makeText(context,text, Toast.LENGTH_SHORT).show();
			} break;
			case MSG_AUTH_ERROR: {
				// 失败
				Throwable t = (Throwable) msg.obj;
				String text = context.getString(R.string.error_system)+":" + t.getMessage();
				Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
				t.printStackTrace();
			} break;
			case MSG_AUTH_COMPLETE: {
				// 成功
				Object[] objs = (Object[]) msg.obj;
				String platName = (String) objs[0];
				HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
//				if (loginListener!= null && loginListener.onLogin(platName, res))
//				{
//					ThreadRegisterActivity.setOnLoginListener(loginListener);
//					ThreadRegisterActivity.setPlatform(platName);
//					Intent intent=new Intent(context, ThreadRegisterActivity.class);
//					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//					context.startActivity(intent);
//				}

				if (platform.equals(Wechat.NAME))
				{
						wechat(platName,res);
				}
				else if (platform.equals(SinaWeibo.NAME))
				{
						weibo(platName,res);
				}
				else if (platform.equals(QQ.NAME))
				{

				}

			} break;

			case MSG_RETURN_TO_LOGIN:
			{
				Object[] objs = (Object[]) msg.obj;
				String platName = (String) objs[0];
				HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
				if (loginListener!= null )
				{
					loginListener.onLogin(platName, res);
				}
			} break;

			case MSG_NET_ERROR:
			{
				// 错误
				if (loginListener!= null)
				{
					Object[] objs = (Object[]) msg.obj;
					Integer code = (Integer) objs[0];
					loginListener.onError(code);
				}
			} break;

			case MSG_RETURN_TO_REG:
			{
				Object[] objs = (Object[]) msg.obj;
				String plat = (String) objs[0];
				@SuppressWarnings("unchecked")
				HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
				String register_way = (String) objs[2];
				if (loginListener!= null)
				{
					ThreadRegisterActivity.setOnLoginListener(loginListener);
					ThreadRegisterActivity.setPlatform(plat);
					Intent intent=new Intent(context, ThreadRegisterActivity.class);
					intent.putExtra("register_way",register_way);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
				}
			} break;
		}
		return false;
	}

	private void wechat(final String platName, final HashMap<String, Object> res)
	{
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String client_key = tm.getDeviceId();

		Platform platformInfo = ShareSDK.getPlatform(platName);
		SystemSet systemSet =  SystemSet.getInstance();
		String	assestoken  = "";
		String	userId  = "";
		String	userName  = "";

		String gender = "";
		if(platformInfo != null){
			assestoken = platformInfo.getDb().getToken();
			userId  = platformInfo.getDb().getUserId();
			systemSet.setAssestoken(assestoken);

			gender = platformInfo.getDb().getUserGender();
			if("m".equals(gender)){
				systemSet.getUserInfo().setUserGender(UserInfo.Gender.MALE);
			}else{
				systemSet.getUserInfo().setUserGender(UserInfo.Gender.FEMALE);
			}

			systemSet.getUserInfo().setUserName(platformInfo.getDb().getUserName());
			systemSet.getUserInfo().setUserIcon(platformInfo.getDb().getUserIcon());
			systemSet.getUserInfo().setUserNote(userId);
		}


		ServerApi.wechat(assestoken, userId, client_key, new ServerCallBack()
		{
			@Override
			public void onError(Request request, Exception e)
			{
				Log.e("onError",e.getMessage());
				Message msg = new Message();
				msg.what = MSG_NET_ERROR;
				msg.obj =  new Object[] {-1};
				handler.sendMessage(msg);
			}

			@Override
			public void onResponse(String response) throws JSONException
			{
				Log.e("......",response.toString());
				JSONObject jsonObject = new JSONObject(response);
				int code =jsonObject.optInt("code");

				try {
					if (0 == code)
					{
						JSONObject objectData = jsonObject.optJSONObject("data");
						String username =  objectData.optString("username");
						String token =  objectData.optString("token");
						String member_id =  objectData.optString("member_id");
						String f_person =  objectData.optString("f_person");
						String auth_personal =  objectData.optString("auth_personal");
						String auth_enterprise =  objectData.optString("auth_enterprise");
						String auth_actor =  objectData.optString("auth_actor");
						String auth_writer =  objectData.optString("auth_writer");

						SystemSet systemSet =  SystemSet.getInstance();
						systemSet.setToken(token);
						systemSet.setMember_id(member_id);
						systemSet.setF_person(f_person);
						systemSet.setAuth_personal(auth_personal);
						systemSet.setAuth_enterprise(auth_enterprise);
						systemSet.setAuth_actor(auth_actor);
						systemSet.setAuth_writer(auth_writer);

						Message msg = new Message();
						msg.what = MSG_RETURN_TO_LOGIN;
						msg.obj =  new Object[] {platName, res};
						handler.sendMessage(msg);
						return;

					}
					else  if (10032 ==(code))
					{
						Message msg = new Message();
						msg.what = MSG_RETURN_TO_REG;
						String register_way = "wechat";
						msg.obj =  new Object[] {platName, res,register_way};
						handler.sendMessage(msg);
						return;
					}
					else
					{
						Message msg = new Message();
						msg.what = MSG_NET_ERROR;
						msg.obj =  new Object[] {code};
						handler.sendMessage(msg);
						return;
					}
				}
				catch (Exception e)
				{
					onError(null,e);
				}

			}
		});
	}


	private void weibo(final String platName, final HashMap<String, Object> res)
	{
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String client_key = tm.getDeviceId();

		Platform platformInfo = ShareSDK.getPlatform(platName);
		SystemSet systemSet =  SystemSet.getInstance();
		String	assestoken  = "";
		String	userId  = "";
		String	userName  = "";

		String gender = "";
		if(platformInfo != null){
			assestoken = platformInfo.getDb().getToken();
			userId  = platformInfo.getDb().getUserId();
			systemSet.setAssestoken(assestoken);

			gender = platformInfo.getDb().getUserGender();
			if("m".equals(gender)){
				systemSet.getUserInfo().setUserGender(UserInfo.Gender.MALE);
			}else{
				systemSet.getUserInfo().setUserGender(UserInfo.Gender.FEMALE);
			}

			systemSet.getUserInfo().setUserName(platformInfo.getDb().getUserName());
			systemSet.getUserInfo().setUserIcon(platformInfo.getDb().getUserIcon());
			systemSet.getUserInfo().setUserNote(userId);
		}

		ServerApi.weibo(assestoken, userId, client_key, new ServerCallBack()
		{
			@Override
			public void onError(Request request, Exception e)
			{
				Log.e("onError",e.getMessage());
				Message msg = new Message();
				msg.what = MSG_NET_ERROR;
				msg.obj =  new Object[] {-1};
				handler.sendMessage(msg);
			}

			@Override
			public void onResponse(String response) throws JSONException
			{
				Log.e("......",response.toString());
				JSONObject jsonObject = new JSONObject(response);
				int code =jsonObject.optInt("code");

				try {
					if (0 == code)
					{
						JSONObject objectData = jsonObject.optJSONObject("data");
						String username =  objectData.optString("username");
						String token =  objectData.optString("token");
						String member_id =  objectData.optString("member_id");
						String f_person =  objectData.optString("f_person");
						String auth_personal =  objectData.optString("auth_personal");
						String auth_enterprise =  objectData.optString("auth_enterprise");
						String auth_actor =  objectData.optString("auth_actor");
						String auth_writer =  objectData.optString("auth_writer");

						SystemSet systemSet =  SystemSet.getInstance();
						systemSet.setToken(token);
						systemSet.setMember_id(member_id);
						systemSet.setF_person(f_person);
						systemSet.setAuth_personal(auth_personal);
						systemSet.setAuth_enterprise(auth_enterprise);
						systemSet.setAuth_actor(auth_actor);
						systemSet.setAuth_writer(auth_writer);

						Message msg = new Message();
						msg.what = MSG_RETURN_TO_LOGIN;
						msg.obj =  new Object[] {platName, res};
						handler.sendMessage(msg);
						return;

					}
					else  if (10032 ==(code))
					{
						Message msg = new Message();
						msg.what = MSG_RETURN_TO_REG;
						String register_way = "weibo";
						msg.obj =  new Object[] {platName, res,register_way};
						handler.sendMessage(msg);
						return;
					}
					else
					{
						Message msg = new Message();
						msg.what = MSG_NET_ERROR;
						msg.obj =  new Object[] {code};
						handler.sendMessage(msg);
						return;
					}
				}
				catch (Exception e)
				{
					onError(null,e);
				}

			}
		});
	}
}
